const {perfromSql,send,sendErr,getToken} =require('../utils/index');
const express=require('express');
const route=express.Router();


route.post('/api/login',async(req,res)=>{
    const {username,password}=req.body;
    if(!username&&!password){
        sendErr(res,'参数错误',req.body)
        return;
    }
    const sql=`select * from user where username=? and password=? limit 1`
    const result=await perfromSql(sql,username,password);
    //错误
    if(result.length===0){
        sendErr(res,'账户或密码错误');
        return;
    }
    //登录成功
    let user={...result[0]};
    delete user.password;
    send(res,{
        token:getToken(user),
        user,
    });
})
route.post('/api/register',async(req,res)=>{
    const {username,password,name}=req.body;
    //判断账户是否存在
    let sql=`select * from user where username=? limit 1`
    let result=await perfromSql(sql,username);
    if(result.length>0){
        sendErr(res,'账户已存在')
        return;
    }
    //注册
    sql=`insert into user set ?`;
    result=await perfromSql(sql,{username,password,name});
    if(result?.affectedRows===1){
        send(res,'注册成功');
        return;
    }
    sendErr(res,'注册失败，未知原因')
})
route.post('/reLogin',async(req,res)=>{
    const user = req.auth
    send(res,user)
})
module.exports=route;